package com.wkbb.basic.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.mapper.EmployeeMapper;
import com.wkbb.basic.mapper.UserInfoMapper;
import com.wkbb.basic.mapper.UserMapper;
import com.wkbb.basic.model.Employee;
import com.wkbb.basic.model.Organization;
import com.wkbb.basic.model.User;
import com.wkbb.basic.model.UserInfo;
import com.wkbb.basic.service.EmployeeService;
import com.wkbb.basic.service.UserInfoService;
import com.wkbb.basic.service.UserService;
import com.wkbb.basic.utils.FillEmptyHeadImgUtil;
import com.wkbb.basic.vo.EmployeeEditInfoVo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.constants.CommonConstant;
import com.wkbb.common.dto.basic.EmployeeInfoDto;
import com.wkbb.common.enums.RoleTypeEnum;
import com.wkbb.common.enums.UserTypeEnum;
import com.wkbb.common.utils.MD5Util;
import com.wkbb.common.utils.StringUtil;
import com.wkbb.common.utils.UuIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    public void setMapper(EmployeeMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    public PageInfo<EmployeeInfoDto> getEmployeePageList(Map<String, Object> params, final Integer pageNo, final Integer pageSize)
    {
        if (pageNo == null || pageSize == null) {
            return null;
        }

        Page<EmployeeInfoDto> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<EmployeeInfoDto> pageInfo = new PageInfo<EmployeeInfoDto>(employeeMapper.getEmployeeInfoPageList(params));
        pageInfo.setTotal(page.getTotal());

        return pageInfo;
    }

    @Override
    public List<EmployeeInfoDto> getEmployeeList(Map<String, Object> params)
    {
        return employeeMapper.getEmployeeInfoPageList(params);
    }

    @Override
    public EmployeeInfoDto getEmployee(Map<String, Object> params)
    {
        EmployeeInfoDto employeeInfo = employeeMapper.getEmployeeInfoByMapParams(params);
        return employeeInfo;
    }

    @Override
    public EmployeeInfoDto getEmployeeInfo(Long orgId, Long userId)
    {
        //查询是否有绑定
        Map<String, Object> employeeParams = new HashMap<String, Object>();
        employeeParams.put("orgId", orgId);
        employeeParams.put("userId", userId);
        EmployeeInfoDto employeeInfo = employeeMapper.getEmployeeInfoByMapParams(employeeParams);
        return employeeInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertEmployee(EmployeeInfoDto employeeInfoDto, String createBy) {
        User user = userMapper.getByPrimaryKey(employeeInfoDto.getUserId());
        Long userId;
        Employee employee;

        String headImg = FillEmptyHeadImgUtil.checkHeadImg(employeeInfoDto.getSex(), RoleTypeEnum.EMPLOYEE.getValue(), employeeInfoDto.getHeadImgUrl(), false);
        if (!StringUtil.isNullOrBlank(headImg)) {
            log.info("默认头像地址：" + headImg);
            employeeInfoDto.setHeadImgUrl(headImg);
        }

        if (null != user) {
            userId = user.getId();

            //插入老师表
            employee = insertEmployee(employeeInfoDto, userId, createBy);

            //有用户信息,修改roleType  JSON权限
            Object roleType = userService.updateRoleTypeJson(user.getRoleType(), null, Short.parseShort("" + RoleTypeEnum.EMPLOYEE.getValue()), null, employeeInfoDto.getOrgId(),user.getId());
            user.setRoleType(roleType);
            userMapper.update(user);

            //更新redis
            userService.updateUserInfo(employeeInfoDto.getOrgId(), userId);

        } else {

            Object roleType = userService.updateRoleTypeJson(null, null, Short.parseShort("" + RoleTypeEnum.EMPLOYEE.getValue()), null, employeeInfoDto.getOrgId(),null);
            User newUser = new User();
            BeanUtils.copyProperties(employeeInfoDto, newUser);
            newUser.setRoleType(roleType);
            newUser.setStatus(true);
            newUser.setUserCode(UuIdUtil.getUserCodeByUUId());
            userService.insert(employeeInfoDto.getOrgId(), newUser, RoleTypeEnum.EMPLOYEE.getValue(), employeeInfoDto.getSex(),UserTypeEnum.OTHER.getValue().shortValue(),employeeInfoDto.getSmartWxUserId(),employeeInfoDto.getIsSmartSubscribe() );

            userId = newUser.getId();

            UserInfo userInfo = new UserInfo();
            BeanUtils.copyProperties(employeeInfoDto, userInfo);
            if(!StringUtils.isEmpty(employeeInfoDto.getHeadImgUrl())) {
                userInfo.setHeadImgMd5(userService.getImageMD5(employeeInfoDto.getHeadImgUrl()));
            }
            userInfo.setUserId(userId);
            userInfoMapper.insert(userInfo);

            employee = insertEmployee(employeeInfoDto, userId, createBy);

        }

        return userId;
    }

    @Override
    public Employee insertEmployee(EmployeeInfoDto employeeInfoDto, Long userId, String createBy) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeInfoDto, employee);
        employee.setUserId(userId);

        fillPosition(employee);
        if(null ==employee.getAccount())
        employee.setAccount(employee.getMobile());
        
        employee.setPassword(MD5Util.getMD5Code(employeeInfoDto.getPassword()));
        employee.setStatus(true);
        employee.setCreateBy(createBy);
        employee.setUpdateBy(createBy);
        employee.setUserType((short)2);
        employeeMapper.insert(employee);

        return employee;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmployee(EmployeeInfoDto employeeInfoDto,String updateBy,boolean isBack,boolean updateAccount) throws Exception
    {
        //当头像为空,默认设置头像.否则走正常变更
        Boolean flag=false;
        if(!StringUtil.isEmptyIgnoreBlank(employeeInfoDto.getHeadImgUrl())){
            flag=true;
        }

        String headImg = FillEmptyHeadImgUtil.checkHeadImg(employeeInfoDto.getSex(), RoleTypeEnum.EMPLOYEE.getValue(), employeeInfoDto.getHeadImgUrl(), flag);
        if (!StringUtil.isNullOrBlank(headImg)) {
            log.info("默认头像地址：" + headImg);
            employeeInfoDto.setHeadImgUrl(headImg);
        }

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeInfoDto, employee);
        if (!StringUtil.isNullOrBlank(employeeInfoDto.getPassword())) {
            employee.setPassword(MD5Util.getMD5Code(employeeInfoDto.getPassword()));
        } else {
            employee.setPassword(null);
        }

        employee.setUpdateBy(updateBy);

        fillPosition(employee);

        //在这里要把employeeInfoDto对象的oriUserType和userType的值也填充
        employeeInfoDto.setOriUserType(employee.getOriUserType());
        employeeInfoDto.setUserType(employee.getUserType());

        if (isBack) {
            employee.setUpdateAccount(updateAccount);//是否修改账号密码
            employeeMapper.updateBack(employee);
        } else {
            employeeMapper.update(employee);
        }

        User user = userMapper.getByPrimaryKey(employeeInfoDto.getUserId());
        BeanUtils.copyProperties(employeeInfoDto, user);
        //employee的ID将user的ID覆盖了，employee的userId才是user的ID
        user.setId(employeeInfoDto.getUserId());
        Object roleType = userService.updateRoleTypeJson(user.getRoleType(), employeeInfoDto.getOriUserType(), Short.parseShort("" + RoleTypeEnum.EMPLOYEE.getValue()), employeeInfoDto.getOldOrgId(), employeeInfoDto.getOrgId(),user.getId());
        user.setRoleType(roleType);
        user.setMobile(employeeInfoDto.getMobile());
        user.setHeadImgUrl(employeeInfoDto.getHeadImgUrl());
        if(null!=employeeInfoDto.getIsSmartSubscribe()){
            user.setIsSmartSubscribe(employeeInfoDto.getIsSmartSubscribe());
        }

        userService.update(employeeInfoDto.getOrgId(), user, RoleTypeEnum.EMPLOYEE.getValue(), isBack,employeeInfoDto.getSmartWxUserId(),employeeInfoDto.getIsSmartSubscribe());

        Map<String, Object> params = new HashMap<>(1);
        params.put("userId", employeeInfoDto.getUserId());
        UserInfo userInfo = userInfoMapper.getByMapParams(params);
        BeanUtils.copyProperties(employeeInfoDto, userInfo);
        if(!StringUtils.isEmpty(employeeInfoDto.getHeadImgUrl())) {
            userInfo.setHeadImgMd5(userService.getImageMD5(employeeInfoDto.getHeadImgUrl()));
        }
        userInfoService.update(userInfo, isBack);

    }

    @Override
    public EmployeeEditInfoVo getEmployeeInfoById(Long id)
    {
        return employeeMapper.getEmployeeInfoById(id);
    }

    @Override
    public List<Map<String, Object>> getTeacherCountStatByOrgId(Long orgId) {
        return employeeMapper.getTeacherCountStatByOrgId(orgId);
    }

    @Override
    public List<Map<String, Object>> getTearcherCountStatByOrgList(List<Organization> organizationList)
    {
        return employeeMapper.getTearcherCountStatByOrgList(organizationList);
    }

    /**
     * 获取岗位ID,将岗位转成oriUserType和userType
     */
    @Override
    public Employee fillPosition(Employee employee) {
        //先查询原来的oriPositionName,也可以获取从前端页面传过来的oriPositionName,暂时先取数据库中的oriPositionName
        String oriPositionName = "";
        if (null!=employee.getOrgId() && null != employee.getUserId()) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("orgId", employee.getOrgId());
            paramMap.put("userId", employee.getUserId());
            Employee oriEmployee = employeeMapper.getByMapParams(paramMap);
            if(null!=oriEmployee){
                oriPositionName = oriEmployee.getPositionName();
            }
        }
        //要不要新增一个oriPositionName字段?
        Long positionId = employee.getPositionId();
        String positionName = employee.getPositionName();
        log.info("----fillPosition----positionId={},positionName={},数据库中oriPositionName={},前端页面传过来的oriPositionName={}",positionId,positionName,oriPositionName,employee.getOriPositionName());
        //设置原来的userType
        if(StringUtil.isNotEmpty(oriPositionName)){
            if (Arrays.asList(CommonConstant.MASTER_NAME_LIST).contains(oriPositionName)){
                employee.setOriUserType(UserTypeEnum.MASTER.getValue().shortValue());
            }else{
                employee.setOriUserType(UserTypeEnum.TEACHER.getValue().shortValue());
            }
        }
        //设置现在的userType
        if (positionId != null && StringUtil.isNotEmpty(positionName)) {
            //31-园长,32-副园长,33-主任,34-财务,35-保健医生,36-级组长,37-主班,38-副班,39-兴趣班老师,40-保育员,41-保安,42-厨房,43-后勤,44-实习老师,45-营养师,46-司机,47-其他
            if (Arrays.asList(CommonConstant.MASTER_NAME_LIST).contains(positionName)){
                employee.setUserType(UserTypeEnum.MASTER.getValue().shortValue());
            }else{
                employee.setUserType(UserTypeEnum.TEACHER.getValue().shortValue());
            }
        }
        log.info("----fillPosition----oriUserType={},userType={}",employee.getOriUserType(),employee.getUserType());

        return employee;
    }
}
